// popup.js - 弹出页面脚本
(function() {
    'use strict';
    
    let currentTables = [];
    
    // DOM元素
    const elements = {
        loading: document.getElementById('loading'),
        error: document.getElementById('error'),
        status: document.getElementById('status'),
        tableCount: document.getElementById('tableCount'),
        tableSelector: document.getElementById('tableSelector'),
        tableSelect: document.getElementById('tableSelect'),
        paginationOption: document.getElementById('paginationOption'),
        collectAllPages: document.getElementById('collectAllPages'),
        progressContainer: document.getElementById('progressContainer'),
        progressFill: document.getElementById('progressFill'),
        progressText: document.getElementById('progressText'),
        buttons: document.getElementById('buttons'),
        exportCsv: document.getElementById('exportCsv'),
        exportExcel: document.getElementById('exportExcel')
    };
    
    // 初始化
    async function init() {
        showLoading();
        try {
            await scanTables();
            setupEventListeners();
        } catch (error) {
            showError('初始化失败: ' + error.message);
        }
    }
    
    // 显示加载状态
    function showLoading() {
        elements.loading.style.display = 'block';
        elements.error.style.display = 'none';
        elements.status.style.display = 'none';
        elements.tableSelector.style.display = 'none';
        elements.buttons.style.display = 'none';
    }
    
    // 显示错误信息
    function showError(message) {
        elements.loading.style.display = 'none';
        elements.error.textContent = message;
        elements.error.style.display = 'block';
        elements.status.style.display = 'none';
        elements.tableSelector.style.display = 'none';
        elements.buttons.style.display = 'none';
    }
    
    // 显示主界面
    function showMainInterface() {
        elements.loading.style.display = 'none';
        elements.error.style.display = 'none';
        elements.status.style.display = 'block';
        elements.tableSelector.style.display = currentTables.length > 1 ? 'block' : 'none';
        elements.buttons.style.display = 'block';
    }
    
    // 扫描当前页面的表格
    async function scanTables() {
        return new Promise((resolve, reject) => {
            chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
                if (chrome.runtime.lastError) {
                    reject(new Error(chrome.runtime.lastError.message));
                    return;
                }
                
                if (!tabs[0]) {
                    reject(new Error('无法获取当前标签页'));
                    return;
                }
                
                chrome.tabs.sendMessage(tabs[0].id, {action: 'getTables'}, (response) => {
                    if (chrome.runtime.lastError) {
                        reject(new Error('无法连接到页面内容脚本，请刷新页面后重试'));
                        return;
                    }
                    
                    if (!response || !response.success) {
                        reject(new Error(response ? response.error : '获取表格数据失败'));
                        return;
                    }
                    
                    currentTables = response.tables || [];
                    updateUI();
                    resolve();
                });
            });
        });
    }
    
    // 更新用户界面
    function updateUI() {
        // 更新表格数量
        elements.tableCount.textContent = currentTables.length;
        
        // 更新表格选择器
        elements.tableSelect.innerHTML = '<option value="all">所有表格</option>';
        
        let hasPaginatedTables = false;
        
        currentTables.forEach((table, index) => {
            const option = document.createElement('option');
            option.value = index;
            
            // 添加分页标识
            let description = table.description;
            if (table.hasPagination && table.hasPagination.hasPagination) {
                description += ' 🔄';
                hasPaginatedTables = true;
            }
            
            option.textContent = description;
            option.dataset.hasPagination = table.hasPagination ? table.hasPagination.hasPagination : false;
            elements.tableSelect.appendChild(option);
        });
        
        // 显示或隐藏导出按钮
        const hasValidTables = currentTables.length > 0;
        elements.exportCsv.disabled = !hasValidTables;
        elements.exportExcel.disabled = !hasValidTables;
        
        if (hasValidTables) {
            showMainInterface();
        } else {
            showError('当前页面没有找到任何表格');
        }
        
        // 更新分页选项显示
        updatePaginationOption();
    }
    
    // 设置事件监听器
    function setupEventListeners() {
        elements.exportCsv.addEventListener('click', () => exportData('csv'));
        elements.exportExcel.addEventListener('click', () => exportData('excel'));
        
        // 表格选择变化时更新分页选项
        elements.tableSelect.addEventListener('change', updatePaginationOption);
    }
    
    // 更新分页选项显示
    function updatePaginationOption() {
        const selectedIndex = elements.tableSelect.value;
        
        if (selectedIndex !== 'all' && selectedIndex >= 0) {
            const selectedOption = elements.tableSelect.options[elements.tableSelect.selectedIndex];
            const hasPagination = selectedOption.dataset.hasPagination === 'true';
            
            if (hasPagination) {
                elements.paginationOption.classList.add('show');
            } else {
                elements.paginationOption.classList.remove('show');
                elements.collectAllPages.checked = false;
            }
        } else {
            elements.paginationOption.classList.remove('show');
            elements.collectAllPages.checked = false;
        }
    }
    
    // 导出数据
    async function exportData(format) {
        try {
            // 获取选中的表格数据
            const selectedIndex = elements.tableSelect.value;
            const shouldCollectAllPages = elements.collectAllPages.checked;
            
            // 如果需要收集分页数据
            if (shouldCollectAllPages && selectedIndex !== 'all') {
                await exportPaginatedData(format, selectedIndex);
            } else {
                await exportRegularData(format, selectedIndex);
            }
            
        } catch (error) {
            showError('导出失败: ' + error.message);
        }
    }
    
    // 导出常规数据
    async function exportRegularData(format, selectedIndex) {
        chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
            chrome.tabs.sendMessage(tabs[0].id, {
                action: 'getTableData',
                tableIndex: selectedIndex
            }, (response) => {
                if (!response || !response.success) {
                    showError('获取表格数据失败: ' + (response ? response.error : '未知错误'));
                    return;
                }
                
                if (format === 'csv') {
                    downloadCsv(response.tables);
                } else if (format === 'excel') {
                    downloadExcel(response.tables);
                }
            });
        });
    }
    
    // 导出分页数据
    async function exportPaginatedData(format, selectedIndex) {
        // 显示进度条
        showProgress();
        
        // 禁用导出按钮
        elements.exportCsv.disabled = true;
        elements.exportExcel.disabled = true;
        
        try {
            chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
                chrome.tabs.sendMessage(tabs[0].id, {
                    action: 'getTableDataWithPagination',
                    tableIndex: selectedIndex
                }, (response) => {
                    hideProgress();
                    
                    // 重新启用导出按钮
                    elements.exportCsv.disabled = false;
                    elements.exportExcel.disabled = false;
                    
                    if (!response || !response.success) {
                        showError('收集分页数据失败: ' + (response ? response.error : '未知错误'));
                        return;
                    }
                    
                    if (format === 'csv') {
                        downloadCsv(response.tables);
                    } else if (format === 'excel') {
                        downloadExcel(response.tables);
                    }
                });
            });
            
            // 开始进度监控
            monitorProgress();
            
        } catch (error) {
            hideProgress();
            elements.exportCsv.disabled = false;
            elements.exportExcel.disabled = false;
            throw error;
        }
    }
    
    // 显示进度条
    function showProgress() {
        elements.progressContainer.classList.add('show');
        elements.progressFill.style.width = '0%';
        elements.progressText.textContent = '正在收集分页数据...';
    }
    
    // 隐藏进度条
    function hideProgress() {
        elements.progressContainer.classList.remove('show');
    }
    
    // 监控进度
    function monitorProgress() {
        const progressInterval = setInterval(() => {
            chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
                chrome.tabs.sendMessage(tabs[0].id, {
                    action: 'getPaginationProgress'
                }, (response) => {
                    if (response && response.success) {
                        elements.progressFill.style.width = response.progress + '%';
                        elements.progressText.textContent = 
                            `正在处理第 ${response.currentPage} 页... (${response.progress}%)`;
                        
                        if (!response.isProcessing || response.progress >= 100) {
                            clearInterval(progressInterval);
                        }
                    }
                });
            });
        }, 1000);
        
        // 最多监控两分钟
        setTimeout(() => {
            clearInterval(progressInterval);
        }, 120000);
    }
    
    // 下载CSV文件
    function downloadCsv(tables) {
        try {
            let csvContent = '';
            
            tables.forEach((table, tableIndex) => {
                if (tables.length > 1) {
                    csvContent += `${table.description}\n\n`;
                }
                
                table.data.forEach(row => {
                    const csvRow = row.map(cell => {
                        // 处理包含逗号、引号或换行的单元格
                        let processedCell = String(cell || '').replace(/"/g, '""');
                        if (processedCell.includes(',') || processedCell.includes('"') || processedCell.includes('\n')) {
                            processedCell = `"${processedCell}"`;
                        }
                        return processedCell;
                    }).join(',');
                    
                    csvContent += csvRow + '\n';
                });
                
                if (tableIndex < tables.length - 1) {
                    csvContent += '\n';
                }
            });
            
            // 添加BOM以支持中文
            const BOM = '\uFEFF';
            const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
            
            downloadFile(blob, 'tables.csv');
            
        } catch (error) {
            showError('生成CSV文件失败: ' + error.message);
        }
    }
    
    // 下载Excel文件
    function downloadExcel(tables) {
        try {
            // 检查是否加载了XLSX库
            if (typeof XLSX === 'undefined') {
                loadXlsxLibrary(() => {
                    generateExcelFile(tables);
                });
                return;
            }
            
            generateExcelFile(tables);
            
        } catch (error) {
            showError('生成Excel文件失败: ' + error.message);
        }
    }
    
    // 加载XLSX库
    function loadXlsxLibrary(callback) {
        const script = document.createElement('script');
        script.src = chrome.extension.getURL('lib/xlsx.mini.js');
        script.onload = callback;
        script.onerror = () => {
            showError('无法加载Excel导出库');
        };
        document.head.appendChild(script);
    }
    
    // 生成Excel文件
    function generateExcelFile(tables) {
        try {
            const workbook = XLSX.utils.book_new();
            
            tables.forEach((table, index) => {
                const worksheetName = tables.length > 1 ? `表格${index + 1}` : '表格数据';
                const worksheet = XLSX.utils.aoa_to_sheet(table.data);
                
                XLSX.utils.book_append_sheet(workbook, worksheet, worksheetName);
            });
            
            // 生成Excel文件
            const excelBuffer = XLSX.write(workbook, { 
                bookType: 'xlsx', 
                type: 'array',
                compression: true
            });
            
            const blob = new Blob([excelBuffer], { 
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
            });
            
            downloadFile(blob, 'tables.xlsx');
            
        } catch (error) {
            showError('生成Excel文件失败: ' + error.message);
        }
    }
    
    // 下载文件
    function downloadFile(blob, filename) {
        try {
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            a.style.display = 'none';
            
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            
            // 延迟释放URL对象
            setTimeout(() => URL.revokeObjectURL(url), 1000);
            
        } catch (error) {
            showError('下载文件失败: ' + error.message);
        }
    }
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', init);
    
})();